'use strict'

import Vue from 'vue';
import {API} from '../config/constants'
import apiurl from '../config/apiurl'
import assign from 'core-js/fn/object/assign'
import noop from 'lodash/noop'
import Env from '../config/env.js'

class WechatUtil {
    constructor() {
        if(Env == 'testing'){
            this.appId = 'wx39c68c1de3b9c473'
        }else if(Env == 'production'){
            this.appId = 'wxf25912d615e1397e'
        }
        // 记住初次load页面时的url
        this.originUrl = location.href.split('#')[0]
        this.jsApiList = [
            'getLocation',
            'openLocation',
            'chooseImage',
            'uploadImage'
        ];
        this.isWxReady = false;
        this.taskQueue = [];
    }

    configSDK() {
        this.isWxReady = false;
        this.taskQueue = [];
        this.setupSDK(false, () => {
            this.handleWxReady();
        });
        this.handleWxConfigError();
    }

    handleWxReady() {
        wx.ready(() => {
            this.isWxReady = true;
            let task;
            while (task = this.taskQueue.shift()) {
                task.call();
            }
        })
    }

    handleWxConfigError() {
        wx.error(res => {
            if (res.errMsg == 'config:invalid signature') {
                this.isWxReady = false;
                this.setupSDK(true, () => {
                    this.handleWxReady()
                });
            }
        })
    }

    /**
     * @param rollback - 回滚模式，使用originUrl签名，解决部分机型不兼容pushState的问题
     */
    setupSDK(rollback = false, onConfig = noop) {
        let timestamp = Math.floor(new Date().getTime() / 1000);
        let nonceStr = 'mauto';

        let getSign = () => {
            return Vue.http.post(apiurl[API.GET_WX_SIGNATURE](), {
                timestamp: timestamp,
                nonceStr: nonceStr,
                url: rollback ?  this.originUrl : location.href.split('#')[0]
            }, {
                credentials: true   //cross domain
            })
        };

        getSign().then(res => {
            res = res.json();
            if (!res.result && res.code == 401) {
                location.href = res.resultData;
                return;
            }
            if (!res.result) {
                return;
            }
            wx.config({
                debug: false,
                appId: this.appId,
                timestamp: timestamp,
                nonceStr: nonceStr,
                signature: res.resultData,
                jsApiList: this.jsApiList
            });
            onConfig.call();
        })
    }

    getLocation(success = noop) {
        let doGetLocation = () => {
            wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                    /**
                     * @type {object} res
                     * @property latitude
                     * @property longitude
                     * @property speed
                     * @property accuracy
                     */
                    success(res);
                }
            })
        };

        if (this.isWxReady) {
            doGetLocation()
        } else {
            this.taskQueue.push(doGetLocation)
        }
    }

    getAddress(success = noop) {
        this.getLocation(function (res) {
            let location = res.latitude + ',' + res.longitude;
            //let key = Env == 'testing'?'8c34d231e8d8d1d468340f9323fcbd74':'ae1c56aa79dfeaaf219eb6f65026a4cc'
            Vue.http.jsonp('http://apis.map.qq.com/ws/geocoder/v1', {
                params: {
                    key: "QIIBZ-EEX6P-EMCDY-LT7LX-7LJM6-OZBI3",//开发密钥
                    location: location,//位置坐标
                    get_poi: "0",//是否返回周边POI列表：1.返回；0不返回(默认)
                    coord_type: "1",//输入的locations的坐标类型,1 GPS坐标
                    parameter: {"scene_type": "tohome", "poi_num": 20},//附加控制功能
                    output: "jsonp"
                }
            }).then(res => {
                let data = res.json();
                if (data.status == 0) {
                    var address = data.result.formatted_addresses.recommend;
                    success(address, location)
                }
            })
        })
    }

    /**
     * @param success {Function} - 选择成功回调函数
     * @param options {Object} - 选项，见微信官方文档
     * @see http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E6.8B.8D.E7.85.A7.E6.88.96.E4.BB.8E.E6.89.8B.E6.9C.BA.E7.9B.B8.E5.86.8C.E4.B8.AD.E9.80.89.E5.9B.BE.E6.8E.A5.E5.8F.A3
     */
    chooseImage(success = noop, options = {}) {
        const defaults = {
            count: 9, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        };
        let doChooseImage = () => {
            wx.chooseImage(assign({}, defaults, options, {
                success
            }))
        };
        if (this.isWxReady) {
            doChooseImage()
        } else {
            this.taskQueue.push(doChooseImage)
        }
    }

    /**
     * @param {number} localId
     * @param {number} isShowProgressTips
     * @param {function} success
     * @desc 上传图片（单张）至微信
     */
    uploadImage(localId, success = noop, isShowProgressTips = 1) {
        let doUploadImage = () => {
            wx.uploadImage({
                localId,
                isShowProgressTips,
                success
            })
        };
        if (this.isWxReady) {
            doUploadImage()
        } else {
            this.taskQueue.push(doUploadImage)
        }
    }

    /**
     * 批量上传图片
     * @param localIds
     * @param success
     * @desc 依次（队列）上传图片，解决iOS下不支持并发上传的问题
     */
    bulkUploadImages(localIds, success = noop) {
        let photos = [];
        let cursor = 0;
        let uploadOneImage = () => {
            if (cursor === localIds.length) {
                success(photos);
                return
            }
            let localId = localIds[cursor];
            this.uploadImage(localId, res => {
                photos.push({
                    local: localId,
                    server: res.serverId
                });
                cursor++;
                uploadOneImage()
            })
        }
        uploadOneImage()
    }

    openLocation(options = {}) {
        const defaults = {
            latitude: 0, // 纬度，浮点数，范围为90 ~ -90
            longitude: 0, // 经度，浮点数，范围为180 ~ -180。
            name: '', // 位置名
            address: '', // 地址详情说明
            scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为最大
            infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
        };
        let doOpenLocation = () => {
            wx.openLocation(assign({}, defaults, options));
        };
        if (this.isWxReady) {
            doOpenLocation()
        } else {
            this.taskQueue.push(doOpenLocation)
        }
    }
}

export default new WechatUtil()
